/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import logic.UserActionsLocal;
import model.GroupDefinition;
import model.User;

/**
 *
 * @author Alexandre
 */
@WebServlet(name="Controller", urlPatterns={"/Controller"})
public class Controller extends HttpServlet {
    @EJB
    private UserActionsLocal userActions;
    private User user;
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            HttpSession session = request.getSession(true);
            String action = request.getParameter("action");
            if(action != null){
                if(action.equals("login")){
                    processLogin(session,request,response);return;
                }else if(action.equals("newaccount")){
                    processNewAccount(request,response);return;
                }else if(action.equals("newreceipt")){
                    processNewReceipt(session,request,response);return;
                }else if(action.equals("newpayment")){
                    processNewPayment(session,request,response);return;
                }else if(action.equals("newgroup")){
                    processNewGroup(session,request,response);return;
                }else if(action.equals("showgroup")){
                    processShowGroup(session,request,response);return;
                }else if(action.equals("joingroup")){
                   processJoinGroup(session,request,response);return;
                }
            }

            session.invalidate();
            RequestDispatcher dis = request.getRequestDispatcher("homePage.jsp");
            dis.forward(request, response);
        } finally { 
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

    private void processNewAccount(HttpServletRequest request, HttpServletResponse response) {
                String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        userActions.addNewUser(username, email, password);
    }

    private void processNewReceipt(HttpSession session,HttpServletRequest request, HttpServletResponse response) {
        if(user == null){
            user =  (User)session.getAttribute("user");
        }
        String concept = request.getParameter("concept");
        float quantity = Float.parseFloat(request.getParameter("quantity"));
        int groupId = Integer.parseInt(request.getParameter("groupId"));
        userActions.addReceipt(user,"", concept, quantity,groupId);
    }

    private void processNewPayment(HttpSession session,HttpServletRequest request, HttpServletResponse response) {
        if(user == null){
            user =  (User)session.getAttribute("user");
        }
        String target = request.getParameter("target");
        float quantity = Float.parseFloat(request.getParameter("quantity"));
        int groupId = Integer.parseInt(request.getParameter("groupId"));
        userActions.addPayment(user,target, quantity,groupId);
    }

    private void processNewGroup(HttpSession session,HttpServletRequest request, HttpServletResponse response) {
         if(user == null){
            user =  (User)session.getAttribute("user");
        }
        String namegroup = request.getParameter("group");
        userActions.createNewGroup(user,namegroup);
    }

    private void processShowGroup(HttpSession session,HttpServletRequest request, HttpServletResponse response) {
          if(user == null){
            user =  (User)session.getAttribute("user");
        }
        int groupId = Integer.parseInt(request.getParameter("groupId"));
        GroupDefinition group = userActions.getGroupPermission(user,groupId);
        if(group != null){
            request.setAttribute("group", group);
            RequestDispatcher req = request.getRequestDispatcher("group.jsp");
            if(req != null){
                try {
                    req.forward(request, response);
                } catch (ServletException ex) {
                    Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                } catch (IOException ex) {
                    Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            
        }
    }

    private void processJoinGroup(HttpSession session,HttpServletRequest request, HttpServletResponse response) {
          if(user == null){
            user =  (User)session.getAttribute("user");
        }
        int groupId = Integer.parseInt(request.getParameter("groupId"));
        GroupDefinition group = userActions.joinGroup(user,groupId);
    }

    private void processLogin(HttpSession session,HttpServletRequest request, HttpServletResponse response) {
        try {
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            user = userActions.loginUser(username, password);
            if(user != null){
                session.setAttribute("user",user);
            }
            response.sendRedirect("homePage.jsp");
        } catch (IOException ex) {
            Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
